<template>
  <el-select
    ref="datestyleRef"
    v-model="value"
    placeholder="请选择"
    :popper-append-to-body="inScreen"
    @change="onChange"
    @visible-change="onVisibleChange"
  >
    <el-option v-for="el in defaultSetting.relativeOptions" :key="el.value" :label="$t(el.text)" :value="el.value">
    </el-option>
  </el-select>
</template>

<script>
import { ApplicationContext } from '@/utils/ApplicationContext'
import bus from '@/utils/bus'
import customInput from '@/components/widget/deWidget/customInput'
import { mapState } from 'vuex'
import { viewEditSave } from '@/api/chart/chart'
export default {
  mixins: [customInput],
  props: {
    canvasId: {
      type: String,
      required: true,
    },
    element: {
      type: Object,
      default: null,
    },
    inDraw: {
      type: Boolean,
      default: true,
    },
    inScreen: {
      type: Boolean,
      required: false,
      default: true,
    },
    size: String,
    isRelation: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      value: '',
      data: null,
      xaxis: null,
      item: null,
    }
  },
  computed: {
    ...mapState(['canvasStyleData']),
    defaultSetting() {
      const widget = ApplicationContext.getService(this.element.serviceName)
      const setting = widget.defaultSetting()
      return setting
    },
  },
  watch: {
    element(newval) {
      this.data = null
      this.xaxis = null
      this.item = null
      bus.$emit('send-data')
    },
  },
  created() {
    bus.$on('chart-data-send', this.getMatchData)
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    getMatchData(data) {
      data = JSON.parse(data)
      let dataId = this.element?.options?.attrs?.fieldsParent?.id
      if (!dataId) return
      let fieldId = this.element.options.attrs.fieldId
      if (data.id === dataId) {
        this.data = data
        let xAxis = JSON.parse(data.xaxis)
        this.xaxis = xAxis
        let index = xAxis.findIndex((el) => el.id === fieldId)
        if (index > -1) {
          this.value = xAxis[index].dateStyle
          this.item = xAxis[index]
        }
      }
    },
    async onChange() {
      if (!this.data) return
      let newVal = this.value
      this.item.dateStyle = newVal
      this.data.xaxis = JSON.stringify(this.xaxis)
      let res = await viewEditSave(this.data.sceneId, this.data)
      if (res.success) {
        bus.$emit('refresh', this.data.id)
      }
    },
    onVisibleChange(val) {
      if (!val) return
      if (!this.data) bus.$emit('send-data')
    },
  },
}
</script>

<style lang="scss"></style>
